import { NEVER, RefinementCtx, z, ZodIssueCode } from 'zod'
import UserService from '@/models/mysql/UserService'

// 检测登录参数，验证用户名和密码
const checkLoginParamObjIsValidUser = async (data: { username: string; password: string }, ctx: RefinementCtx) => {
  const { username, password } = data
  // 查找用户
  try {
    const user = await UserService.getUserInfoByUsername(username, ['username', 'crypt_pwd', 'status'])
    if (!user || !(await user.validatePassword(password))) {
      ctx.addIssue({
        code: ZodIssueCode.custom,
        path: ['username', 'password'],
        message: '用户名不存在或密码错误',
        fatal: true
      })
      return NEVER
    }
    // 用户状态检查
    if (!user.isActive()) {
      ctx.addIssue({ code: ZodIssueCode.custom, path: ['username'], message: '该用户已被禁用' })
    }
  } catch (error) {
    ctx.addIssue({ code: ZodIssueCode.custom, fatal: true, path: ['username', 'password'], message: '服务异常' })
    return NEVER
  }
}

// 定义Zod模式
const loginSchema = z
  .object({
    username: z
      .string({ errorMap: () => ({ message: '请输入5~20位登录用户名' }) })
      .min(5)
      .max(20),
    password: z
      .string({ errorMap: () => ({ message: '请输入5~30位登录密码' }) })
      .min(5)
      .max(30)
  })
  .superRefine(checkLoginParamObjIsValidUser)

export default { loginSchema }
